﻿Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Text
Imports System.Data.SqlClient
Imports System.Data
Imports System.Data.OleDb

Public Class TagCloud

    Public Shared Sub getTagCloud(ByVal stringSqlDataSource As SqlDataSource, ByVal literalCtr As Literal, ByRef pageRef As Page)
        literalCtr.Text = "<div id='LinksForTags'>"

        'Read data from Datasource
        Dim cloudData As DataView = CType(stringSqlDataSource.Select(DataSourceSelectArguments.Empty), DataView)

        'Determine each category weight
        Const SpacerMarkup As String = " "      'The markup injected between each item in the cloud
        Dim FontScale() As String = {"x-small", "small", "medium", "large", "x-large", "xx-large"}

        'Database columns
        Const WeightColumnName As String = "TotalTags"
        Const TextColumnName As String = "Tag"
        Const NavigateUrlColumnName As String = "Tag"
        Const NavigateUrlFormatString As String = "~/BeachesByTag.aspx?Tag={0}"

        Dim minWeight As Decimal = 10000
        Dim maxWeight As Decimal = -10000

        For Each row As DataRowView In cloudData
            Dim numTagsObj As Object = row(WeightColumnName)
            If Not Convert.IsDBNull(numTagsObj) Then
                Dim numTagsDec As Decimal = Convert.ToDecimal(numTagsObj)

                If numTagsDec < minWeight Then minWeight = numTagsDec
                If numTagsDec > maxWeight Then maxWeight = numTagsDec
            End If
        Next
        'Output each category, using a font size relative to its place on the scale
        Dim scaleUnitLength As Decimal = (maxWeight - minWeight + 1) / Convert.ToDecimal(FontScale.Length)

        For Each row As DataRowView In cloudData
            Dim numTagsObj As Object = row("TotalTags")
            If Not Convert.IsDBNull(numTagsObj) Then
                Dim numTagsDec As Decimal = Convert.ToDecimal(numTagsObj)
                Dim scaleValue As Integer = Math.Truncate((numTagsDec - minWeight) / scaleUnitLength)
                literalCtr.Text &= String.Format("<a href=""{0}"" style=""font-size:{1};"">{2}</a>{3}",
                                            pageRef.ResolveUrl(String.Format(NavigateUrlFormatString, row(NavigateUrlColumnName).ToString())),
                                            FontScale(scaleValue), row(TextColumnName).ToString(), SpacerMarkup)
            End If
        Next
        literalCtr.Text &= "</div>"
        cloudData.Dispose()
        stringSqlDataSource.Dispose()
    End Sub
End Class
